// #ifdef H5
import wx from 'jweixin-module';
// #endif
let MIXIN = {
	data() {
		return {
			sharePubtitle: '多米街',
			sharepath: '',
			shareimageUrl: '',
			sharequery: '',
			urlKf: '', //客服链接
		}
	},
	onLoad(options) {
		let mid = '';
		if (options.mid) {
			mid = options.mid;
		}
		if (options.scene) {
			let scene = decodeURIComponent(options.scene);
			mid = this.gup('mid', scene);
		}
		if (mid != '') {
			uni.setStorageSync('mid', mid);
		}
		this.getSharePath();
	},
	onShow() {
		// #ifdef H5
		this.shareItem()
		// #endif
	},
	methods: {
		// 获取页面路由
		getFullCurrentRoute() {
			const pages = getCurrentPages();
			if (pages.length === 0) return '';
			// 当前页面实例
			const currentPage = pages[pages.length - 1];
			// 获取页面路径（部分环境中路径存放在 currentPage.route 中）
			const pagePath = currentPage.route || '';

			// 获取参数（页面 onLoad 接收的 options 会保存在 currentPage.options 中）
			const query = currentPage.options || {};

			// 拼接参数（处理编码）
			const paramStr = Object.entries(query)
				.map(([key, value]) => {
					// 确保值为字符串（避免数字/布尔类型直接拼接）
					const val = typeof value === 'string' ? value : String(value);
					return `${encodeURIComponent(key)}=${encodeURIComponent(val)}`;
				})
				.join('&');

			// 完整路由（路径 + 参数）
			return paramStr ? `/${pagePath}?${paramStr}` : `/${pagePath}`;
		},
		// 保存图片
		async saveImg(img) {
			uni.downloadFile({
				url: img,
				success: function(url) {
					uni.saveImageToPhotosAlbum({
						filePath: url.tempFilePath,
						success: function(e) {
							uni.showToast({
								title: '图片保存成功',
								duration: 2200
							});
						},
					});
				}
			});
		},
		async getKf(type) {
			let res = await this.$axios('home/kf', 'post', 'shop')
			if (res.data.code == 200) {
				this.urlKf = res.data.data
				uni.setStorageSync('kf', this.urlKf);
				if (type == 'get') {
					if (!this.urlKf) {
						uni.showToast({
							title: '打开客服链接失败请重试',
							icon: 'none'
						});
						return
					}
					uni.navigateTo({
						url: "/pages/web/web-view?type=kf"
					})
				}
			}
		},
		copyText(textToCopy) {
			uni.setClipboardData({
				data: String(textToCopy),
				success: () => {
					uni.showToast({
						title: '复制成功',
						icon: 'success'
					});
				},
				fail: (err) => {
					console.error('复制失败:', err);
					uni.showToast({
						title: '复制失败',
						icon: 'none'
					});
				}
			});
		},
		getSharePath(val = '', auto = false) {
			let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
			// 需要获取转发URL的页面路由
			let pathArr = [{
					type: 'home',
					child: []
				},
				{
					type: 'goods',
					child: ['/pages/product/product']
				},
				{
					type: 'other',
					child: []
				}
			];
			// 禁止转发的路由页面
			let banPath = [
				'/pages/index/index', '/pages/my/index', '/pages/rule/index', '/pages/order/createOrder',
				'/pages/order/detailsx'
			];
			// 禁止传参数的路由页面
			let banParam = ['/pages/user/hb'];
			if (routes.length > 0 && routes[routes.length - 1].$page) {
				// 判断是手动还是自动获取url参数
				if (!auto) {
					this.sharepath = routes[routes.length - 1].$page.fullPath; //获取当前页面路由
				} else {
					this.sharepath = val;
				}
				console.log(this.sharepath);
				// 禁用页面转发
				banPath.forEach(item => {
					// if(item.search(this.sharepath.split('?')[0])!=-1){
					if (item == this.sharepath.split('?')[0]) {
						// console.log(this.sharepath)
						uni.hideShareMenu();
						console.log('页面禁止分享')
						return;
					}
				})
				// #ifdef MP-ALIPAY
				console.log('支付宝全局禁止分享')
				uni.hideShareMenu();
				// #endif
				let type;
				let cid = routes[routes.length - 1].options.id ? routes[routes.length - 1].options.id : 0;
				pathArr.forEach((item) => {
					item.child.forEach((items) => {
						// if(this.sharepath.includes(items)){
						if (this.sharepath.split('?')[0] == items) {
							type = item.type;
							// 去掉多余参数，在cid已经传过
							banParam.forEach(itemss => {
								if (itemss == items) {
									this.sharepath = this.sharepath.split('?')[0];
								}
							})
							this.$axios('Group/getConfig', 'POST', 'group_buy', {
								url: this.sharepath,
								type,
								cid
							}).then(res => {
								if (res.data.code == 200) {
									if (res.data.data.shareinfo.title) {
										this.sharePubtitle = res.data.data.shareinfo.title;
									}
									this.sharepath = res.data.data.shareinfo.url;
									this.sharequery = res.data.data.shareinfo.url.split(
										'?')[1];
									this.shareimageUrl = res.data.data.shareinfo.imgurl;
								}
							})
						}
					})
				})
			}
		},
		gup(name, url) {
			if (url) url = url ? '?' + url : location.href;
			name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
			var regexS = "[\\?&]" + name + "=([^&#]*)";
			var regex = new RegExp(regexS);
			var results = regex.exec(url);
			return results == null ? null : results[1];
		},
		checkTitle(data) {
			let status = false;
			let arr = ['水费', '话费', '电费', '燃气', '信用卡', '高铁'];
			if (data) {
				for (let i = 0; i < arr.length; i++) {
					if (data.search(arr[i]) != -1) {
						status = true;
						break;
					}
				}
			}
			return status;
		},
		// 微信公众号分享
		async shareItem(url = '') {
			const newUrl = url ? url : this.getUrlWithoutMid(window.location.href)
			const res = await this.$axios('WxInfo/getConfig', 'POST', 'shop', {
				url: newUrl,
				type: 'pintuan'
			})
			if (res.data.code == 200) {
				this.initWxConfig(res.data.data)
			}

		},
		initWxConfig(data) {
			const title = '消费享补贴，就用多米街';
			wx.config({
				debug: false,
				appId: data.config.appId,
				nonceStr: data.config.nonceStr,
				timestamp: data.config.timestamp,
				signature: data.config.signature,
				jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline', 'updateAppMessageShareData',
					'updateTimelineShareData'
				]
			})
			wx.ready(function() {
				wx.onMenuShareAppMessage({
					title: data.shareinfo.title || title,
					desc: data.shareinfo.desc,
					link: data.shareinfo.url,
					imgUrl: data.shareinfo.imgurl,
					type: 'link',
					success: () => {
						console.log('分享配置设置成功1', data.shareinfo.url)
					}
				})
				wx.updateAppMessageShareData({
					title: data.shareinfo.title || title,
					desc: data.shareinfo.desc,
					link: data.shareinfo.url,
					imgUrl: data.shareinfo.imgurl,
					success: () => {
						console.log('分享配置设置成功2', data.shareinfo.url)
						// this.handleShare(data)
					}
				})
				wx.onMenuShareTimeline({
					title: data.shareinfo.title || title, // 分享标题 
					link: data.shareinfo.url, // 分享链接  
					imgUrl: data.shareinfo.imgurl, // 分享图标
					success: function() {
						console.log('朋友圈分享成功1', data.shareinfo.url)
					},
				});
				wx.updateTimelineShareData({
					title: data.shareinfo.title || title, // 分享标题 
					link: data.shareinfo.url, // 分享链接  
					imgUrl: data.shareinfo.imgurl, // 分享图标
					success: function() {
						console.log('朋友圈分享成功2', data.shareinfo.url)
					},
				});


			})
			wx.error(function(res) {
				console.log('微信分享错误', res);
			});
		},
		// 去除mid参数
		getUrlWithoutMid(currentUrl) {
			// 拆分URL为基础部分和哈希部分（#后面的内容）
			const [basePart, hashPart = ''] = currentUrl.split('#');

			// 拆分哈希部分为路径和参数
			const [hashPath, queryString = ''] = hashPart.split('?');

			// 如果没有参数，直接返回重组的URL
			if (!queryString) {
				return `${basePart}#${hashPath}`;
			}

			// 解析参数，过滤掉mid
			const paramsArray = queryString.split('&').filter(param => {
				const [key] = param.split('=');
				return key !== 'mid'; // 排除mid参数
			});

			// 重组参数部分
			const newQueryString = paramsArray.length > 0 ? `?${paramsArray.join('&')}` : '';

			// 重组完整URL
			return `${basePart}#${hashPath}${newQueryString}`;
		}
	},
	// #ifdef MP-WEIXIN
	//转发分享
	onShareAppMessage() {
		console.log(this.sharepath);
		return {
			title: this.sharePubtitle,
			path: this.sharepath,
			imageUrl: this.shareimageUrl
		}
	},
	onShareTimeline() {
		return {
			title: this.sharePubtitle,
			// path: this.path,
			query: this.sharequery,
			imageUrl: this.shareimageUrl
		}
	}
	// #endif
};
export default MIXIN;